package com.example.demo.advice;

import com.example.demo.common.response.SSPTResponse;
import com.example.demo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常拦截
 * @author farben
 */
@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public SSPTResponse<String> handleValidException(Exception e) {
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        } else {
            bindingResult = ((BindException) e).getBindingResult();
        }

        StringBuilder validMsg = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            validMsg.append(fieldError.getDefaultMessage()).append("; ");
        }
        log.error("参数验证异常:{}",validMsg.toString());

        SSPTResponse<String> ssptResponse = new SSPTResponse<>();
        ssptResponse.setCode(1);
        ssptResponse.setMessage(validMsg.toString());
        return ssptResponse;
    }

    @ResponseBody
    @ExceptionHandler({BusinessException.class})
    public SSPTResponse<String> handleBusinessException(BusinessException ex) {
        log.error("业务异常",ex);
        SSPTResponse<String> ssptResponse = new SSPTResponse<>();
        ssptResponse.setCode(1);
        ssptResponse.setMessage(ex.getMessage());
        return ssptResponse;
    }

    @ResponseBody
    @ExceptionHandler({Exception.class})
    public SSPTResponse<String> handleException(Exception ex) {
        log.error("未知异常",ex);
        SSPTResponse<String> ssptResponse = new SSPTResponse<>();
        ssptResponse.setCode(1);
        ssptResponse.setMessage("服务器内部异常,请联系管理员");
        return ssptResponse;
    }

}
